package com.youdoneed.common.application;

import com.youdoneed.base.application.DateStringConverter;
import com.youdoneed.base.application.GlobalExceptionResolver;
import com.youdoneed.base.application.StringDateConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.convert.converter.Converter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.annotation.PostConstruct;
import java.util.Date;

@Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {

    public static Logger logger = LoggerFactory.getLogger(WebConfigurer.class);

    @Autowired
    private DispatcherServlet dispatcherServlet;

    @PostConstruct
    public void initThreadContext() {
        // 使其在异步线程中也能正常使用RequestContext
        dispatcherServlet.setThreadContextInheritable(true);
    }

    /**
     * 全局异常处理。
     */
    @Bean
    public GlobalExceptionResolver globalExceptionResolver() {
        return new GlobalExceptionResolver();
    }

    /**
     * 国际化资源绑定到容器和请求上下文，使用Header中的Accept-Language。
     */
    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setUseCodeAsDefaultMessage(true);
        messageSource.setBasename("messages/message");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public Converter<String, Date> stringDateConvert() {
        return new StringDateConverter();
    }

    @Bean
    public Converter<Date, String> dateStringConvert() {
        return new DateStringConverter();
    }

}